//
//  ViewController.m
//  测试demo
//
//  Created by ycx on 2019/6/27.
//  Copyright © 2019 ycx. All rights reserved.
//

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "DataModel.h"

double DegreesToRadians(double degrees) {return degrees * M_PI / 180;};
double RadiansToDegrees(double radians) {return radians * 180 / M_PI;};

static NSString * mapData = @"mapData";

@interface ViewController ()<CLLocationManagerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *latitudeLab;
@property (weak, nonatomic) IBOutlet UILabel *longitudeLab;
@property (weak, nonatomic) IBOutlet UILabel *heightLab;
@property (weak, nonatomic) IBOutlet UILabel *speedLab;
@property (weak, nonatomic) IBOutlet UILabel *courseLab;
@property (weak, nonatomic) IBOutlet UILabel *timeLab;
@property (weak, nonatomic) IBOutlet UITextField *remarkText;


@property (nonatomic ,strong) CLLocationManager* locationManager;
@property(nonatomic,strong)CLLocation * prevLocation;
@property(nonatomic,assign)NSTimeInterval sumTime;
@property(nonatomic,assign)CGFloat sumDistance;
@property(nonatomic,assign)CGFloat currentSpeed;
@property(nonatomic,assign)CGFloat avgSpeed;
@property(nonatomic,copy)NSString * currentdirection;
@property(nonatomic,strong)NSTimer * locationTimer;

@property(nonatomic,assign)double  magneticHeading;
@property(nonatomic,assign)CGFloat magneticHeadingAngel;

@property(nonatomic,assign)double  trueHeading;
@property(nonatomic,assign)double  headingAccuracy;
@property(nonatomic,assign)double  headingX;
@property(nonatomic,assign)double  headingY;
@property(nonatomic,assign)double  headingZ;






@end

@implementation ViewController
- (IBAction)locationBtnClick:(id)sender {
    UIButton * btn = (UIButton *)sender;
    
    
    if([btn.titleLabel.text isEqualToString:@"开启定位"])
    {
        [btn setTitle:@"停止定位" forState:UIControlStateNormal];
        
        self.locationTimer = [NSTimer timerWithTimeInterval:0.1 target:self selector:@selector(startLocationService) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.locationTimer forMode:NSRunLoopCommonModes];

    }else
    {
       
        [self.locationTimer invalidate];
        [btn setTitle:@"开启定位" forState:UIControlStateNormal];
        NSMutableArray * dataArray = [[[NSUserDefaults standardUserDefaults] objectForKey:mapData] mutableCopy];
        NSString * text = [self ArrayToJSON:dataArray];
        NSLog(@"%@",text);
        
    }
}
-(void)startLocationService
{
   // NSLog(@"定时器掉用");
    //如果定位服务可用
    if ([CLLocationManager locationServicesEnabled]) {
        NSLog(@"开始执行定位服务");
        self.locationManager.pausesLocationUpdatesAutomatically = NO;
        //设置定位精度：最佳精度
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置距离过滤器为50米，表示每移动50米更新一次位置
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
        self.locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //将试图控制器自身设置为CLLocationManager的delegate
        //因此该试图控制器需要实现CLLocationManagerDelegate协议
        self.locationManager.delegate = self;
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        {
            [self.locationManager requestWhenInUseAuthorization];
            [self.locationManager requestAlwaysAuthorization];
        }
        if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
        {
            self.locationManager.allowsBackgroundLocationUpdates = YES;
        }
        //开始监听定位信息
        [self.locationManager startUpdatingLocation];
        // 如果磁力计可用，则开始监听方向改变
        if([CLLocationManager headingAvailable])
        {
            self.locationManager.headingFilter = kCLHeadingFilterNone;
            [self.locationManager startUpdatingHeading];
        }
    }else{
        NSLog(@"无法使用定位服务！！！");
    }
    
}
-(void)stopLocationService
{
    //开始监听定位信息
    [self.locationManager stopUpdatingLocation];
    [self.locationManager stopUpdatingHeading];
}



-(void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading{
    
    
    // magneticHeading : 距离磁北方向的角度
    // trueHeading : 真北
    // headingAccuracy : 如果是负数,代表当前设备朝向不可用
    if (newHeading.headingAccuracy < 0) {
        return;
    }
    /**
     * magneticHeading 表示磁北极偏转的角度
     ＊trueHeading  磁北极的真实角度
     ＊0.0 - 359.9 度, 0 being true North
     */
    
    
 
    
    
    
    self.magneticHeading = newHeading.magneticHeading;
    
//    NSString *direction = [NSString string];
//    if (self.magneticHeading < 90) {
//        direction = @"北";
//    }else if (self.magneticHeading > 90 && self.magneticHeading < 180){
//        direction = @"东";
//        self.magneticHeading = self.magneticHeading - 90;
//    }else if (self.magneticHeading > 180 && self.magneticHeading < 270){
//        direction = @"南";
//    }else if (self.magneticHeading > 270){
//        direction = @"西";
//        self.magneticHeading = self.magneticHeading - 270;
//    }
   
    //将我们的角度转换为弧度
    CGFloat angle= newHeading.magneticHeading/180.0*M_PI;
    self.magneticHeadingAngel = angle;
    self.trueHeading = newHeading.trueHeading;
    self.headingAccuracy = newHeading.headingAccuracy;
    self.headingX = newHeading.x;
    self.headingY = newHeading.y;
    self.headingZ = newHeading.z;
    
  NSLog(@"磁北:%f,磁北弧度:%f,真北:%f,偏移:%f,x方向:%f,y方向:%f,z方向:%f",self.magneticHeading,self.magneticHeadingAngel,self.trueHeading,self.headingAccuracy,self.headingX,self.headingY,self.headingZ);
    
    [self.locationManager stopUpdatingHeading];
    
}

-(BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager
{
    return YES;
}

#pragma mark -- CLLocationManagerDelegate
//成功获取定位数据后将会激发该方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //获取最后一个定位数据
    CLLocation* newLocation = [locations lastObject];
    //依次获取CLLocation中封装的经度、纬度、高度、速度、方向等信息
    
    

        self.prevLocation = newLocation;
        NSDate * date = self.prevLocation.timestamp;
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CH"];
        fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *temp = [fmt stringFromDate:date];
    
        NSMutableArray * dataArray = [[[NSUserDefaults standardUserDefaults] objectForKey:mapData] mutableCopy];
        if(dataArray.count>0)
        {
        
            NSMutableDictionary * dataDic =[[NSMutableDictionary alloc] init];
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.coordinate.latitude] forKey:@"latitude"];//纬度
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.coordinate.longitude] forKey:@"longitude"];//精度
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.altitude] forKey:@"altitude"];//高度
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.speed] forKey:@"speed"];//设备移动速度
            //有GPS硬件的设备可以获取设备的移动的航向.
            /*
             course当前设备前进的方向
             0°表示向北
             90°表示向东
             180°表示向南
             270°表示向西
             */
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.course] forKey:@"course"];//设备移动航向  0° 值表示正北方向， 90°值表示正东方向， 180° 值表示正南方向， 270° 值表示正西方向
            [dataDic setObject:temp forKey:@"timestamp"];//定位时间
            
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.magneticHeading] forKey:@"magneticHeading"];//该属性返回设备与磁北的相对方向。
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.trueHeading] forKey:@"trueHeading"];//该属性返回设备与真北的相对方向。   提示： 真北始终指向地理北极点；磁北则对应于随时间变化的地球磁场北极。 iOS 系统使用一个计算后的偏移量（称为偏差）来确定这两者之间的差异。
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.headingAccuracy] forKey:@"headingAccuracy"];//该属性返回方向值的误差范围
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.headingX] forKey:@"headingX"];//获取该设备在 X 方向上监听得到的原始磁力值，该磁力值的强度单位是微特斯拉。
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.headingY] forKey:@"headingY"];//获取该设备在 Y 方向上监听得到的原始磁力值，该磁力值的强度单位是微特斯拉。
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.headingZ] forKey:@"headingZ"];//获取该设备在 Z 方向上监听得到的原始磁力值，该磁力值的强度单位是微特斯拉。
            [dataArray addObject:dataDic];
            [[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:mapData];
            
            
            
            
        }else
        {
            dataArray = [[NSMutableArray alloc] init];
            NSMutableDictionary * dataDic =[[NSMutableDictionary alloc] init];
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.coordinate.latitude] forKey:@"latitude"];
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.coordinate.longitude] forKey:@"longitude"];
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.altitude] forKey:@"altitude"];
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.speed] forKey:@"speed"];
            [dataDic setObject:[NSString stringWithFormat:@"%g",self.prevLocation.course] forKey:@"course"];
            [dataDic setObject:temp forKey:@"timestamp"];
            
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.magneticHeading] forKey:@"magneticHeading"];
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.trueHeading] forKey:@"trueHeading"];
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.headingAccuracy] forKey:@"headingAccuracy"];
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.headingX] forKey:@"headingX"];
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.headingY] forKey:@"headingY"];
            [dataDic setObject:[NSString stringWithFormat:@"%f",self.headingZ] forKey:@"headingZ"];
            

            [dataArray addObject:dataDic];
            [[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:mapData];
            
            
        }
        
       
        self.latitudeLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.coordinate.latitude];
        self.longitudeLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.coordinate.longitude];
        self.heightLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.altitude];
        self.speedLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.speed];
        self.courseLab.text = [NSString stringWithFormat:@"%g",self.prevLocation.course];
        self.timeLab.text = temp;
      //NSLog(@"经度:%g,纬度:%g,高度:%g,速度:%g,方向:%g",self.prevLocation.coordinate.latitude,self.prevLocation.coordinate.longitude,self.prevLocation.altitude,self.prevLocation.speed,self.prevLocation.course);
    
       [self.locationManager stopUpdatingLocation];

}
//定位失败时激发的方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"定位失败：%@",error);
}
-(void)DicRemark:(NSString *)text
{
    NSMutableArray * dataArray = [[[NSUserDefaults standardUserDefaults] objectForKey:mapData] mutableCopy];
    NSMutableDictionary * dic = [[dataArray lastObject] mutableCopy];
    [dic setObject:text forKey:@"remarkText"];
    [dataArray replaceObjectAtIndex:dataArray.count-1 withObject:dic];
    [[NSUserDefaults standardUserDefaults]  setObject:dataArray forKey:mapData];
    self.remarkText.text = @"";
    [self startLocationService];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
   
    [self.remarkText resignFirstResponder];
    if(self.remarkText.text.length>0)
    {
         [self stopLocationService];
        [self DicRemark:self.remarkText.text];
        
    }
    
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
   

    [textField resignFirstResponder];
    
    if(textField.text.length>0)
    {
       
        [self stopLocationService];
        
        [self DicRemark:textField.text];
    }
    
    return YES;
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.remarkText.delegate = self;
}
- (NSString *)ArrayToJSON:(NSArray *)Arr {
    
    
    NSData *data=[NSJSONSerialization dataWithJSONObject:Arr options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    //去除空格和回车：
//    jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonStr;
}
-(CLLocationManager *)locationManager
{
    if(!_locationManager)
    {
        _locationManager = [[CLLocationManager alloc] init];
    }
    return _locationManager;
}


@end
